package com.aramco.fion.util
{
	import flash.display.DisplayObject;
	import flash.events.IEventDispatcher;
	import flash.events.MouseEvent;
	
	import mx.core.IFlexDisplayObject;
	import mx.events.CloseEvent;
	import mx.managers.PopUpManager;
	
	import org.swizframework.core.Swiz;
	import org.swizframework.events.BeanEvent;

	public class PopupHelper
	{
		public function PopupHelper()
		{
		}
		/**
		 * Show popup content and register view bean with Swiz (so [Inject] works)
		 * Attach listener to closure to cleanup and close popup when the "close" event is detected 
		 */
		public static function showPopup(dispatcher:IEventDispatcher, parentUI:DisplayObject, component:Class ):void
		{
			/**
			 * Closure/callback use to close the popup and unregister the swiz bean
			 */
			function onClosePopup(e:CloseEvent):void
			{
				var who : IFlexDisplayObject = e.target as IFlexDisplayObject;
				who.removeEventListener(CloseEvent.CLOSE,onClosePopup);
				
				PopUpManager.removePopUp(who);
				dispatcher.dispatchEvent(new BeanEvent(BeanEvent.TEAR_DOWN_BEAN,who));	
			}
			
			var target:IFlexDisplayObject = PopUpManager.createPopUp(parentUI,component);
			target.addEventListener(CloseEvent.CLOSE,onClosePopup,false,0,true);
			
			PopUpManager.centerPopUp(target);
			dispatcher.dispatchEvent(new BeanEvent(BeanEvent.SET_UP_BEAN,target));
		}
	}
}